package com.zhaotianhao.userservice.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhaotianhao.userservice.common.JsonResult;
import com.zhaotianhao.userservice.dto.UserDTO;
import com.zhaotianhao.userservice.entity.User;
import com.zhaotianhao.userservice.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Z-7
 * @since 2022-05-16
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Value("${jwt.key}")
    private String jwtKey;

    @Autowired
    private IUserService iUserService;

    @PostMapping("login")
    public JsonResult login(@RequestBody UserDTO userDTO) {
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",userDTO.getPhone());
        User login = iUserService.getOne(queryWrapper);
        if (login == null) {
            return JsonResult.faild("手机号或密码错误");
        }
        // 密码加密
        String password = SecureUtil.md5(userDTO.getPassword());
        System.out.println(password);
        if (!password.equals(login.getPassword())) {
            return JsonResult.faild("手机号或密码错误");
        }
        // 登录成功 生成token
        String token = JWT.create().setKey(jwtKey.getBytes())
                .setPayload("username", login.getUsername())
                .setPayload("role", login.getRole())
                .setExpiresAt(DateUtil.offsetDay(DateUtil.date(), 1))
                .sign();
        return JsonResult.successd(token);
    }
}
